<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px" label-position="top">
        <el-row :gutter="24">
          <el-col :span="6" :xs="24">
            <el-form-item :label="$t('用户姓名')">
              <el-input v-model="page.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item :label="$t('手机号码')">
              <el-input v-model="page.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item :label="$t('营销APP')">
              <el-select style="width: 100%" v-model="page.appId" clearable>
                <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                           :value="item.appId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item :label="$t('营销状态')">
              <el-select style="width: 100%" v-model="page.status" clearable>
                <el-option v-for="item in marketStatusList" :key="item.key" :label="item.value"
                           :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item :label="$t('跟进次数')">
              <el-input v-model="page.followUpNum">
                <template #prepend>
                  <el-select style="width: 60px" v-model="page.followUpSymbol">
                    <el-option v-for="item in symbolList" :key="item.label" :label="item.label"
                               :value="item.value"></el-option>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item :label="$t('营销结果')">
              <el-cascader
                  style="width: 100%"
                  v-model="page.causeKey"
                  :options="selectCause"
                  :props="{ checkStrictly: true,value:'key',label:'value' }"
                  clearable></el-cascader>
            </el-form-item>
          </el-col>

          <el-col :span="6" :xs="24">
            <el-form-item :label="$t('客户类型')">
              <el-select style="width: 100%" v-model="page.type" clearable>
                <el-option :label="$t('数据用户')" :value="1"></el-option>
                <el-option :label="$t('流量用户')" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('分单时间')">
              <el-date-picker
                  style="width: 100%"
                  v-model="page.distributeTime"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('最新跟进时间')" label-width="100px">
              <el-date-picker
                  style="width: 100%"
                  v-model="page.followUpTime"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item :label="$t('注册时间')">
              <el-date-picker
                  style="width: 100%"
                  v-model="page.registerTime"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px" style="margin-top:40px">
              <el-button type="primary" @click="getTableData">{{ $t('查询') }}</el-button>
              <el-button @click="resetSearch">{{ $t('重置') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <Table :table-column="tableColumn" :tableData="tableData" :page="page"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
    >
      <template #status="{row}">
        {{ marketStatusList.find(item => item.key === row.status).value }}
      </template>
      <template #cause="{row}">
        <span v-if="row.cause1">
         {{ renderCause(row) }}
        </span>
      </template>
      <template #phone="{row}">
        <el-popover
            placement="bottom"
            trigger="hover"
        >
          <template #reference>
            <el-button type="text">{{ encryptPhone(row.phone, 'phone') }}</el-button>
          </template>
          <div class="call_phone_box_item" @click="addCallRecord(row,0)">{{ $t('三方应用呼叫') }}</div>
          <div class="call_phone_box_item" @click="addCallRecord(row,1)">{{ $t('打开whatsAPP') }}</div>
        </el-popover>
      </template>
      <template #email="{row}">
        <el-link :underline="false" type="primary" :href="'mailto:' + row.eMail">{{
            encryptPhone(row.eMail, 'email')
          }}
        </el-link>
      </template>
      <template #app="{row}">
        <el-button type="text" @click="openWhatsapp(row)">{{ encryptPhone(row.app, 'phone') }}</el-button>
      </template>
      <template #handle="{row}">
        <el-button type="text" @click="addRemark(row)">{{ $t('新增备注') }}</el-button>
        <el-button type="text" @click="lookRemark(row)">{{ $t('查看备注') }}</el-button>
      </template>
    </Table>

    <Dialog :title="$t('查看备注')" v-model="remarkVisible" :footer="false">
      <Table :table-column="remarkColumn" :tableData="remarkData" :page="remarkPage"
             @handleCurrentChange="(val)=>{page.pageNum = val,getRemarkList()}"
             @handleSizeChange="(val)=>{page.pageSize = val,getRemarkList()}"
      >
        <template #cause="{row}">
        <span v-if="row.cause1">
         {{ renderCause(row) }}
        </span>
        </template>
      </Table>
    </Dialog>

    <Dialog :title="$t('新增备注')" v-model="addRemarkVisible" @cancel="addRemarkVisible= false"
            @confirm="addRemarkConfirm"
            @close="addRemarkClear"
    >
      <el-form ref="addRemarkFormRef" :model="addRemarkForm" label-width="80px">
        <el-form-item :label="$t('营销结果')" :rules="[
              {required:true,message:$t('请选择'),trigger: 'change',type:'array'}
          ]" prop="causeKey">
          <el-cascader
              style="width: 100%"
              v-model="addRemarkForm.causeKey"
              :options="selectCause"
              :props="{value:'key',label:'value' }"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remarks">
          <el-input type="textarea" v-model="addRemarkForm.remarks" :rows="4"/>
        </el-form-item>
      </el-form>
    </Dialog>

  </el-card>
</template>

<script>
import {nextTick, onMounted, reactive, ref, toRefs} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {selectProductList, selectSystemUser} from "@/api";
import {dateFormatTimeStamp, getMarketCause} from "@/utils/index"
import i18n from "@/locale";
import {
  fetchMarketingAgencyList,
  fetchMarketingRemarkslist,
  addCallClickRecord,
  marketingAddRemarks
} from "@/api/market"

const $t = i18n.global.t
const tableColumn = [
  {label: $t('客户类型'), prop: 'type', align: 'center', minWidth: 100},
  {label: $t('用户姓名'), prop: 'name', align: 'center', minWidth: 100},
  {label: $t('手机号码'), prop: 'phone', align: 'center', minWidth: 100, slot: 'phone'},
  {label: $t('邮箱'), prop: 'email', align: 'center', minWidth: 100, slot: 'email'},
  {label: $t('whatsAPP'), prop: 'app', align: 'center', minWidth: 100, slot: 'app'},
  {label: $t('分单时间'), prop: 'creationTime', align: 'center', minWidth: 150},
  {label: $t('注册时间'), prop: 'registerTime', align: 'center', minWidth: 150},
  {label: $t('营销状态'), prop: 'status', slot: 'status', align: 'center'},
  {label: $t('营销结果'), prop: 'cause', slot: 'cause', align: 'center', minWidth: 150},
  {label: $t('跟进次数'), prop: 'followUpNum', align: 'center'},
  {label: $t('最新跟进时间'), prop: 'followUpTime', align: 'center', minWidth: 150},
  {label: $t('营销APP'), prop: 'appName', align: 'center', minWidth: 100},
  {label: $t('操作'), slot: 'handle', align: 'center', fixed: 'right', minWidth: 150},
]
const remarkColumn = [
  {label: $t('跟进时间'), prop: 'creationTime', align: 'center'},
  {label: $t('营销结果'), prop: 'cause', slot: 'cause', align: 'center'},
  {label: $t('备注'), prop: 'remarks', align: 'center'},
  {label: $t('营销员'), prop: 'systemUserName', align: 'center'},
]
export default {
  name: "index",
  setup() {
    const addRemarkFormRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        followUpSymbol:'='
      },
      remarkPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      productList: [],
      marketStatusList: [
        {key: 1, value: $t('未注册')},
        {key: 2, value: $t('未申请')},
      ],
      remarkData: [],
      symbolList: [
        {label: '>', value: '>'},
        {label: '=', value: '='},
        {label: '≧', value: '>='},
        {label: '≦', value: '<='},
        {label: '<', value: '<'}
      ],
      remarkVisible: false,
      tableRows: {},
      selectCause: formatCause(getMarketCause()),
      transferOrderVisible: false,
      addRemarkVisible: false,
      addRemarkForm: {
        causeKey: null,
        remarks: null
      }
    })

    function formatCause(value) {
      return value.filter(item => {
        if (item.code === 0) {
          const children = value.filter(child => child.type === item.type && child.code !== 0)
          if (children.length > 0) item.children = children
          return item.code === 0
        }
      })
    }

    const methods = {
      async getTableData() {
        const [distributeTimeStart, distributeTimeEnd] = dateFormatTimeStamp(state.page.distributeTime)
        const [followUpTimeStart, followUpTimeEnd] = dateFormatTimeStamp(state.page.followUpTime)
        const [registerTimeStart, registerTimeEnd] = dateFormatTimeStamp(state.page.registerTime)
        const [cause1, cause2] = state.page.causeKey || []
        const params = {
          distributeTimeStart, distributeTimeEnd,
          followUpTimeStart, followUpTimeEnd,
          registerTimeStart, registerTimeEnd,
          cause1, cause2,
          ...state.page,
          distributeTime: null,
          followUpTime: null,
          registerTime: null,
          causeKey: null
        }
        console.log(state.selectCause)
        const res = await fetchMarketingAgencyList(params)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list.map(item => {
            item.type = item.type === 1 ? $t('数据用户') : $t('流量用户')
            return item
          })
          state.page.total = total
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0,
          followUpSymbol:'='
        }
        methods.getTableData()
      },
      lookRemark(rows) {
        state.tableRows = {...rows}
        methods.getRemarkList()
        state.remarkVisible = true
      },
      addRemark(rows) {
        state.tableRows = {...rows}
        state.addRemarkVisible = true
      },
      renderCause(row) {
        const {value: cause1} = getMarketCause().find(item => item.key === row.cause1)
        const {value: cause2} = getMarketCause().find(item => item.key === row.cause2)
        return cause1 ? cause1 + ' - ' + cause2 : ''
      },
      addRemarkConfirm() {
        addRemarkFormRef.value.validate(async v => {
          if (v) {
            const [cause1, cause2] = state.addRemarkForm.causeKey
            const params = {
              cause1, cause2,
              dataId: state.tableRows.id,
              remarks: state.addRemarkForm.remarks
            }
            const res = await marketingAddRemarks(params)
            if (res.code === 200) {
              state.addRemarkVisible = false
              methods.getTableData()
            }
          }

        })
      },
      addRemarkClear() {
        addRemarkFormRef.value.resetFields()
      },
      async getRemarkList() {
        const res = await fetchMarketingRemarkslist({...state.remarkPage, dataId: state.tableRows.id})
        if (res.code === 200) {
          const {list, total} = res.data
          state.remarkData = list
          state.remarkPage.total = total
        }
      },
      getSelect() {
        selectProductList().then(res => {
          state.productList = res.data
        })
      },
      /**
       *
       * @param rows
       * @param type 0 phone 1 whatsapp/zalo
       */
      async addCallRecord(rows, type) {
        await addCallClickRecord({
          dataType: type,
          dataId: rows.id,
          distributionTime: rows.creationTime,
        })
        if (type === 0) {
          const a = document.createElement('a')
          a.href = 'sip:' + rows.phone + ',' + new Date().getTime()
          a.click()
        } else if (type === 1) {
          methods.openWhatsapp(rows)
        }
      },
      openWhatsapp(rows) {
        const href = `https://web.whatsapp.com/send?phone=+52${rows.app}`
        window.open(href)
      },
      encryptPhone(value, type) {
        if (!value) return ""
        let newValue = ''
        if (type === 'phone') {
          newValue = value.substr(0, 3) + '*******'
        } else {
          const str = value.split("@")
          newValue = str[0].substr(0, str[0].length - (str[0].length - 3)) + "*****" + '@' + str[1]
        }
        return newValue
      }
    }
    onMounted(() => {
      methods.getTableData()
      methods.getSelect()
    })
    return {
      addRemarkFormRef,
      tableColumn,
      remarkColumn,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
